import json
from logging import Logger

from nicegui import ui

from ThresholdParams import ThresholdParams


class ThresholdParamsCtl:
    def __init__(self, logger: Logger, algo_id: str, callback_update_aggrid):
        self.slider_thresh = None
        self.number_step = None
        self.input_max = None
        self.input_min = None
        self.logger = logger
        self.current_params = ThresholdParams()
        self.algo_id = algo_id
        self.callback = callback_update_aggrid

    def get_current_params(self):
        return self.current_params

    def handle_save_params(self):
        self.current_params.minval = self.input_min.value
        self.current_params.maxval = self.input_max.value
        self.current_params.step = self.number_step.value
        self.current_params.thresh = self.slider_thresh.value
        self.logger.debug(f'saved params={self.current_params}')
        self.callback(self.algo_id, ThresholdParams.model_dump_json(self.current_params))

    def build_ui(self,  json_threshold_params: str):
        self.current_params = ThresholdParams.model_validate_json(json_threshold_params)
        self.logger.debug(f'ThresholdParamsCtl current params={self.current_params}')

        with ui.row().classes('item-center justify-between'):
            ui.label('ThresholdParamsCtl').classes('text-bold')
            ui.button("保存", on_click=self.handle_save_params).props('size=sm outline')
        with ui.row():
            self.input_min = ui.input('MIN', value=self.current_params.minval)
            self.input_max = ui.input('MAX', value=self.current_params.maxval)
            self.number_step = ui.number(label='Step', value=self.current_params.step, format='%d')
            self.slider_thresh = ui.slider(min=self.current_params.minval,
                                           max=self.current_params.maxval,
                                           step=self.current_params.step,
                                           value=self.current_params.thresh).props('label-always').on(
                'update:model-value',
                lambda e: ui.notify(e.args),
                throttle=1.0,
                leading_events=False)
